package Java基础.线程池;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * @Title 提供一个服务查询各大电商网站同一类产品的价格并返回汇总展示
 * @Author zhengqiang.tan
 * @Date 2021/3/28 3:16 PM
 */
public class T01_CompletableFuture {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        CompletableFuture<Double> featureTM = CompletableFuture.supplyAsync(() -> priceOfTM());
        CompletableFuture<Double> featurePDD = CompletableFuture.supplyAsync(() -> priceOfPDD());
        CompletableFuture<Double> featureJD = CompletableFuture.supplyAsync(() -> priceOfJD());

        // allOf等待所有异步线程任务结束
        CompletableFuture.allOf(featureJD, featurePDD, featureTM).join();

//        CompletableFuture.supplyAsync(() -> priceOfJD())
//                .thenApply(String::valueOf)
//                .thenApply(str -> "price" + str)
//                .thenAccept(System.out::println);
        // 所有任务运行完成，打印耗时
        System.out.println(System.currentTimeMillis() - start);

//        try {
//            System.in.read();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

    }

    private static Double priceOfTM() {
        delay("priceOfTM");
        return 100.0;
    }

    private static Double priceOfPDD() {
        delay("priceOfPDD");
        return 60.0;
    }

    private static Double priceOfJD() {
        delay("priceOfJD");
        return 120.0;
    }

    private static void delay(String p) {
        int time = new Random().nextInt(1000);
        try {
            TimeUnit.MILLISECONDS.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.printf("%s After sleep %s \n", p,time);
    }
}
